package com.example.lj.uav.view;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;

import com.example.lj.uav.MyApplication;
import com.example.lj.uav.R;
import com.example.lj.uav.adapter.MediaLibraryAdapter;
import com.example.lj.uav.utils.Constants;
import com.example.lj.uav.utils.OnUIUtils;
import com.example.lj.uav.view.base.BaseActivity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import dji.common.camera.SettingsDefinitions;
import dji.common.camera.StorageState;
import dji.common.error.DJICameraError;
import dji.common.error.DJIError;
import dji.common.util.CommonCallbacks;
import dji.log.DJILog;
import dji.sdk.base.BaseProduct;
import dji.sdk.camera.Camera;
import dji.sdk.media.FetchMediaTask;
import dji.sdk.media.FetchMediaTaskContent;
import dji.sdk.media.FetchMediaTaskScheduler;
import dji.sdk.media.MediaFile;
import dji.sdk.media.MediaManager;

import static com.example.lj.uav.MyApplication.mPref;

public class MediaLibraryActivity extends BaseActivity implements Handler.Callback, View.OnClickListener {
    private Spinner mSpCamera;
    private RecyclerView mRevMedia;

    private List<Camera> cameras;
    private Camera selectedCamera;
    private List<String> cameraNames;
    private List<MediaFile> mediaFileList;
    private MediaLibraryAdapter adapter;
    private Handler mHandler;
    private int selectedCameraPosition;

    private static final int SD_CARD = 0;
    private static final int INNER_STORAGE = 1;
    private PopupWindow popupWindowList;
    private PopupWindow popupWindowFilter;
    private ImageView mIvList;
    private ImageView mIvFilter;
    private ImageView mIvDelete;
    private boolean isOrderRise;
    private ProgressBar mPbFetch;
    private SettingsDefinitions.StorageLocation location;
    private MediaManager manager;
    //
    private String TAG = "info";
//    private int lastClickViewIndex;
//    private View lastClickView;
    private FetchMediaTaskScheduler scheduler;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_media_library);
        initView();

    }

    @Override
    protected void onResume() {
        super.onResume();
        initCameras();
    }

    private void initView() {
        mHandler = new Handler(this);
        mSpCamera = findViewById(R.id.sp_media_library_camera);
        mIvList = findViewById(R.id.iv_media_library_list);
        mIvFilter = findViewById(R.id.iv_media_library_filter);
        mRevMedia = findViewById(R.id.rev_media_library);
        mPbFetch = findViewById(R.id.pb_media_fetching);
        mIvDelete = findViewById(R.id.iv_media_library_delete);
        mIvFilter.setOnClickListener(this);
        mIvList.setOnClickListener(this);
        mIvDelete.setOnClickListener(this);
        findViewById(R.id.iv_media_library_back).setOnClickListener(this);

        initList();
    }

    private void initCameras() {
        cameraNames = new ArrayList<>();
        BaseProduct product = MyApplication.getProductInstance();
        if (product != null) {
            cameras = product.getCameras();
            if (cameras != null && cameras.size() > 0) {
                for (int i = 0; i < cameras.size(); i++) {
                    cameraNames.add(cameras.get(i).getDisplayName());
                }
            }
        } else {
            return;
        }
        ArrayAdapter cameraAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, cameraNames);
        cameraAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mSpCamera.setAdapter(cameraAdapter);
        mSpCamera.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, final long l) {
                mPbFetch.setVisibility(View.VISIBLE);
                selectedCamera = cameras.get(position);
                selectedCameraPosition = position;
                initMediaManager();

//                selectedCamera.setMode(SettingsDefinitions.CameraMode.MEDIA_DOWNLOAD, new CommonCallbacks.CompletionCallback() {
//                    @Override
//                    public void onResult(DJIError djiError) {
//                        if (djiError != null) {
//                            OnUIUtils.setToast(djiError.toString());
//                            getMediaList(selectedCamera);
//                        }
//                    }
//                });
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }

//    private void getMediaList(final Camera camera) {
//        files = new ArrayList<>();
//        manager = camera.getMediaManager();
//        if (manager != null) {
//            camera.setStorageStateCallBack(new StorageState.Callback() {
//                @Override
//                public void onUpdate(@NonNull StorageState storageState) {
//                    location = storageState.getStorageLocation();
//                    if (location == SettingsDefinitions.StorageLocation.INTERNAL_STORAGE) {
//                        OnUIUtils.setToast("内部存储");
//                    } else if (location == SettingsDefinitions.StorageLocation.SDCARD) {
//                        OnUIUtils.setToast("SD卡");
//                    } else {
//                        OnUIUtils.setToast("获取存储信息失败");
//                    }
//                }
//            });
//
//            manager.refreshFileList(new CommonCallbacks.CompletionCallback() {
//                @Override
//                public void onResult(DJIError djiError) {
//                    if (djiError != null) {
//                        OnUIUtils.setToast(djiError.toString());
//                    }
//                }
//            });
//
//            if (location != null) {
//                manager.refreshFileListOfStorageLocation(location, new CommonCallbacks.CompletionCallback() {
//                    @Override
//                    public void onResult(DJIError djiError) {
//                        if (djiError != null) {
//                            OnUIUtils.setToast(djiError.toString());
//                            files.clear();
//                            if (location == SettingsDefinitions.StorageLocation.INTERNAL_STORAGE) {
//                                files = manager.getSDCardFileListSnapshot();
//                            } else if (location == SettingsDefinitions.StorageLocation.SDCARD) {
//                                files = manager.getInternalStorageFileListSnapshot();
//                            }
//                            if (files == null || files.size() == 0) {
//                                OnUIUtils.setToast("没有媒体文件");
//                            } else {
//                                mHandler.sendEmptyMessage(Constants.FETCH_MEDIA_FILE_SUCCESS);
//                            }
//                        }
//                    }
//                });
//            }
//            manager.addUpdateFileListStateListener(new MediaManager.FileListStateListener() {
//                @Override
//                public void onFileListStateChange(MediaManager.FileListState fileListState) {
//                    OnUIUtils.setToast(fileListState.toString());
//                    if (fileListState == MediaManager.FileListState.UP_TO_DATE) {
//                        OnUIUtils.setToast("文件状态为UP_TO_DATE");
//                    } else if (fileListState == MediaManager.FileListState.INCOMPLETE) {
//                        OnUIUtils.setToast("文件状态为INCOMPLETE");
//                    } else if (fileListState == MediaManager.FileListState.RESET) {
//                        OnUIUtils.setToast("文件状态为RESET");
//                    } else if (fileListState == MediaManager.FileListState.DELETING) {
//                        OnUIUtils.setToast("文件状态为DELETING");
//                    }
//                }
//            });
//        }
//    }

    private void initList() {
        if (adapter == null) {
            //获取屏幕宽度算出列表的列数
            WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
            DisplayMetrics dm = new DisplayMetrics();
            wm.getDefaultDisplay().getMetrics(dm);
            int width = dm.widthPixels;         // 屏幕宽度（像素）
            int height = dm.heightPixels;       // 屏幕高度（像素）
            float density = dm.density;         // 屏幕密度（0.75 / 1.0 / 1.5）
            int densityDpi = dm.densityDpi;     // 屏幕密度dpi（120 / 160 / 240）
            // 屏幕宽度算法:屏幕宽度（像素）/屏幕密度
            int screenWidth = (int) (width / density);  // 屏幕宽度(dp)
            int screenHeight = (int) (height / density);// 屏幕高度(dp)
            int itemHeight = width / 5;
            mediaFileList = new ArrayList<>();
            adapter = new MediaLibraryAdapter(mediaFileList,  mHandler);
            GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 5);
            mRevMedia.setLayoutManager(gridLayoutManager);
            mRevMedia.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public boolean handleMessage(Message message) {
        switch (message.what) {
            case Constants.OPEN_MEDIA_FILE:
                int position = message.arg1;
                MediaFile file = mediaFileList.get(position);
                MediaFile.MediaType type = file.getMediaType();
                Intent intent = new Intent(MediaLibraryActivity.this, PhotoBrowserActivity.class);
//                intent.putExtra("files", (Serializable) mediaFileList);
                MyApplication.setSavedMediaFiles(mediaFileList);
                intent.putExtra("position", position);
                intent.putExtra("camera", selectedCameraPosition);
                startActivity(intent);
                break;
//            case Constants.FETCH_MEDIA_FILE_SUCCESS:
//                initList();
//                mPbFetch.setVisibility(View.GONE);
//                break;
            case Constants.START_SELECTING_FILES:
                mIvDelete.setVisibility(View.VISIBLE);
                mIvFilter.setVisibility(View.GONE);
                mIvList.setVisibility(View.GONE);
                break;
            case Constants.START_DELETING_FILES:
                List<MediaFile> deleteFiles = (List<MediaFile>) message.obj;
                manager.deleteFiles(deleteFiles, new CommonCallbacks.CompletionCallbackWithTwoParam<List<MediaFile>, DJICameraError>() {
                    @Override
                    public void onSuccess(List<MediaFile> mediaFiles, DJICameraError djiCameraError) {
                        manager.refreshFileListOfStorageLocation(location, new CommonCallbacks.CompletionCallback() {
                            @Override
                            public void onResult(DJIError djiError) {
                                if (djiError != null) {
                                    OnUIUtils.setToast(djiError.toString());
                                }
                            }
                        });
                        mediaFileList.clear();
                        mediaFileList.addAll(mediaFiles);
                        adapter.notifyDataSetChanged();
                        OnUIUtils.setToast("删除成功");
                    }

                    @Override
                    public void onFailure(DJIError djiError) {

                    }
                });
                break;
        }
        return false;
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_media_library_list:
                showListPopupWindow();
                break;
            case R.id.iv_media_library_filter:
                showFilterPopupWindow();
                break;
            case R.id.iv_media_library_back:
                finish();
                break;
            case R.id.iv_media_library_delete:
                adapter.removeSelectedItem();
                break;
        }
    }

    private void showFilterPopupWindow() {
        View view = LayoutInflater.from(this).inflate(R.layout.popup_media_library_filter, null);
        RadioGroup rg = view.findViewById(R.id.rg_media_library_filter);
        RadioButton rb1 = view.findViewById(R.id.rb_media_filter_all);
        RadioButton rb2 = view.findViewById(R.id.rb_media_filter_video);
        RadioButton rb3 = view.findViewById(R.id.rb_media_filter_photo);
        Drawable drawable1 = getResources().getDrawable(R.drawable.selector_media_radio_button);
        Drawable drawable2 = getResources().getDrawable(R.drawable.selector_media_radio_button);
        Drawable drawable3 = getResources().getDrawable(R.drawable.selector_media_radio_button);
        drawable1.setBounds(0, 0, 34, 34);
        drawable2.setBounds(0, 0, 34, 34);
        drawable3.setBounds(0, 0, 34, 34);
        rb1.setCompoundDrawables(null, null, drawable1, null);
        rb2.setCompoundDrawables(null, null, drawable2, null);
        rb3.setCompoundDrawables(null, null, drawable3, null);
        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                switch (i) {
                    case R.id.rb_media_filter_all:
                        adapter.fillList(mediaFileList);
                        break;
                    case R.id.rb_media_filter_video:
                        List<MediaFile> videos = new ArrayList<>();
                        for (int j = 0; j < mediaFileList.size(); j++) {
                            MediaFile.MediaType type = mediaFileList.get(j).getMediaType();
                            if (type == MediaFile.MediaType.JPEG || type == MediaFile.MediaType.RAW_DNG
                                    || type == MediaFile.MediaType.TIFF || type == MediaFile.MediaType.PANORAMA
                                    || type == MediaFile.MediaType.SHALLOW_FOCUS) {
                                videos.add(mediaFileList.get(j));
                            }
                        }
                        if (videos.size() > 0) {
                            adapter.fillList(videos);
                        } else {
                            showToast("没有视频文件");
                        }
                        break;
                    case R.id.rb_media_filter_photo:
                        List<MediaFile> photos = new ArrayList<>();
                        for (int j = 0; j < mediaFileList.size(); j++) {
                            MediaFile.MediaType type = mediaFileList.get(j).getMediaType();
                            if (type == MediaFile.MediaType.MP4 || type == MediaFile.MediaType.MOV
                                    || type == MediaFile.MediaType.SEQ || type == MediaFile.MediaType.TIFF_SEQ) {
                                photos.add(mediaFileList.get(j));
                            }
                        }
                        if (photos.size() > 0) {
                            adapter.fillList(photos);
                        }
                        showToast("没有照片文件");
                        break;
                }
            }
        });
        if (popupWindowFilter == null) {
            popupWindowFilter = new PopupWindow(view, 300, RadioGroup.LayoutParams.WRAP_CONTENT, true);
        }
        popupWindowFilter.setTouchable(true);
        popupWindowFilter.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                return false;
            }
        });

        popupWindowFilter.setBackgroundDrawable(getResources().getDrawable(R.drawable.popup_grey_bg));
        popupWindowFilter.showAsDropDown(mIvList, 0, -60);
    }

    private void showListPopupWindow() {
        View view = LayoutInflater.from(this).inflate(R.layout.popup_media_list, null);
        RadioGroup rg = view.findViewById(R.id.rg_media_list);
        RadioButton rb1 = view.findViewById(R.id.rb_media_list_name);
        RadioButton rb2 = view.findViewById(R.id.rb_media_list_date);
        RadioButton rb3 = view.findViewById(R.id.rb_media_list_size);
        RadioButton rb4 = view.findViewById(R.id.rb_media_list_type);
        LinearLayout ll = view.findViewById(R.id.ll_media_list_order);
        final CheckBox cb = view.findViewById(R.id.cb_media_list_order);
        Drawable drawable1 = getResources().getDrawable(R.drawable.selector_media_radio_button);
        Drawable drawable2 = getResources().getDrawable(R.drawable.selector_media_radio_button);
        Drawable drawable3 = getResources().getDrawable(R.drawable.selector_media_radio_button);
        Drawable drawable4 = getResources().getDrawable(R.drawable.selector_media_radio_button);
        drawable1.setBounds(0, 0, 34, 34);
        drawable2.setBounds(0, 0, 34, 34);
        drawable3.setBounds(0, 0, 34, 34);
        drawable4.setBounds(0, 0, 34, 34);
        rb1.setCompoundDrawables(null, null, drawable1, null);
        rb2.setCompoundDrawables(null, null, drawable2, null);
        rb3.setCompoundDrawables(null, null, drawable3, null);
        rb4.setCompoundDrawables(null, null, drawable4, null);
        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                switch (i) {
                    case R.id.rb_media_list_name:
                        listByName();
                        break;
                    case R.id.rb_media_list_date:
                        listByTime();
                        break;
                    case R.id.rb_media_list_size:
                        listBySize();
                        break;
                    case R.id.rb_media_list_type:
                        listByType();
                        break;
                }
                popupWindowList.dismiss();
            }
        });
        Drawable drawable5 = getResources().getDrawable(R.drawable.selector_media_check_box);
        drawable5.setBounds(0, 0, 34, 34);
        cb.setCompoundDrawables(null, null, drawable5, null);
        cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                isOrderRise = b;
            }
        });
        ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb.setChecked(!cb.isChecked());
            }
        });
        if (popupWindowList == null) {
            popupWindowList = new PopupWindow(view, 300, RadioGroup.LayoutParams.WRAP_CONTENT, true);
        }
        popupWindowList.setTouchable(true);
        popupWindowList.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                return false;
            }
        });

        popupWindowList.setBackgroundDrawable(getResources().getDrawable(R.drawable.popup_grey_bg));
        popupWindowList.showAsDropDown(mIvList, 0, -60);
    }

    private void listByName() {
        List<MediaFile> list = adapter.getDataList();
        if (list.size() > 0) {
            Collections.sort(list, new Comparator<MediaFile>() {
                @Override
                public int compare(MediaFile mediaFile, MediaFile t1) {
                    String name1 = mediaFile.getFileName();
                    String name2 = t1.getFileName();
                    int a = Integer.parseInt(name1.substring(4, name1.length()));
                    int b = Integer.parseInt(name2.substring(4, name2.length()));
                    long diff;
                    if (isOrderRise) {
                        diff = a - b;
                    } else {
                        diff = b - a;
                    }
                    if (diff > 0) {
                        return 1;
                    } else if (diff < 0) {
                        return -1;
                    }
                    return 0;
                }
            });
            adapter.notifyDataSetChanged();
        }
    }

    private void listByTime() {
        List<MediaFile> list = adapter.getDataList();
        if (list.size() > 0) {
            Collections.sort(list, new Comparator<MediaFile>() {
                @Override
                public int compare(MediaFile mediaFile, MediaFile t1) {
                    long diff;
                    if (isOrderRise) {
                        diff = mediaFile.getTimeCreated() - t1.getTimeCreated();
                    } else {
                        diff = t1.getTimeCreated() - mediaFile.getTimeCreated();
                    }
                    if (diff > 0) {
                        return 1;
                    } else if (diff < 0) {
                        return -1;
                    }
                    return 0;
                }
            });
            adapter.notifyDataSetChanged();
        }
    }

    private void listBySize() {
        List<MediaFile> list = adapter.getDataList();
        if (list.size() > 0) {
            Collections.sort(list, new Comparator<MediaFile>() {
                @Override
                public int compare(MediaFile mediaFile, MediaFile t1) {
                    long size1 = mediaFile.getFileSize();
                    long size2 = t1.getFileSize();
                    long diff;
                    if (isOrderRise) {
                        diff = size1 - size2;
                    } else {
                        diff = -size1 + size2;
                    }
                    if (diff > 0) {
                        return 1;
                    } else if (diff < 0) {
                        return -1;
                    }
                    return 0;
                }
            });
            adapter.notifyDataSetChanged();
        }
    }

    private void listByType() {
        List<MediaFile> list = adapter.getDataList();
        if (list.size() > 0) {
            Collections.sort(list, new Comparator<MediaFile>() {
                @Override
                public int compare(MediaFile mediaFile, MediaFile t1) {
                    MediaFile.MediaType type1 = mediaFile.getMediaType();
                    MediaFile.MediaType type2 = t1.getMediaType();
                    long diff;
                    if (isOrderRise) {
                        diff = type1.value() - type2.value();
                    } else {
                        diff = -type1.value() + type2.value();
                    }
                    if (diff > 0) {
                        return 1;
                    } else if (diff < 0) {
                        return -1;
                    }
                    return 0;
                }
            });
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (adapter.isSelecting) {
                adapter.isSelecting = false;
                adapter.selectedFiles.clear();
                adapter.notifyDataSetChanged();
                mIvDelete.setVisibility(View.GONE);
                mIvFilter.setVisibility(View.VISIBLE);
                mIvList.setVisibility(View.VISIBLE);
                return false;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    //以下为按文档中的写的
    @Override
    protected void onDestroy() {
        if (cameras != null && cameras.size() > 0) {
            for (int i = 0; i < cameras.size(); i++) {
                cameras.get(i).setMode(SettingsDefinitions.CameraMode.SHOOT_PHOTO, new CommonCallbacks.CompletionCallback() {
                    @Override
                    public void onResult(DJIError djiError) {
                        if (djiError != null) {
                            OnUIUtils.setToast("Set Shoot Photo Mode Failed" + djiError.getDescription());
                        }
                    }
                });
            }
        }
        if (manager != null) {
            manager.stop(null);
            manager.removeFileListStateCallback(this.updateFileListStateListener);
//            manager.removeMediaUpdatedVideoPlaybackStateListener(updatedVideoPlaybackStateListener);
            manager.exitMediaDownloading();
            if (scheduler!=null) {
                scheduler.removeAllTasks();
            }
        }
        super.onDestroy();
    }

    private void showProgressDialog() {
        runOnUiThread(new Runnable() {
            public void run() {
                if (mPbFetch != null) {
                    mPbFetch.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    private void hideProgressDialog() {
        runOnUiThread(new Runnable() {
            public void run() {
                if (null != mPbFetch && mPbFetch.getVisibility() == View.VISIBLE) {
                    mPbFetch.setVisibility(View.GONE);
                }
            }
        });
    }

    private MediaManager.FileListState currentFileListState;
    private MediaManager.FileListStateListener updateFileListStateListener = new MediaManager.FileListStateListener() {
        @Override
        public void onFileListStateChange(MediaManager.FileListState state) {
            currentFileListState = state;
        }
    };

    private void initMediaManager() {
        if (MyApplication.getProductInstance() == null) {
            mediaFileList.clear();
            adapter.notifyDataSetChanged();
            DJILog.e(TAG, "Product disconnected");
            return;
        } else {
            if (null != selectedCamera && selectedCamera.isMediaDownloadModeSupported()) {
                manager = selectedCamera.getMediaManager();
                if (null != manager) {
                    manager.addUpdateFileListStateListener(this.updateFileListStateListener);
//                    manager.addMediaUpdatedVideoPlaybackStateListener(this.updatedVideoPlaybackStateListener);
                    selectedCamera.setMode(SettingsDefinitions.CameraMode.MEDIA_DOWNLOAD, new CommonCallbacks.CompletionCallback() {
                        @Override
                        public void onResult(DJIError error) {
                            if (error == null) {
                                DJILog.e(TAG, "Set cameraMode success");
                                showProgressDialog();
                                getFileList();
                            } else {
                                OnUIUtils.setToast("Set cameraMode failed");
                            }
                        }
                    });
                    if (manager.isVideoPlaybackSupported()) {
                        DJILog.e(TAG, "Camera support video playback!");
                    } else {
                        OnUIUtils.setToast("Camera does not support video playback!");
                    }
                    scheduler = manager.getScheduler();
                }
            } else if (null != selectedCamera
                    && !selectedCamera.isMediaDownloadModeSupported()) {
                OnUIUtils.setToast("Media Download Mode not Supported");
            }
        }
        return;
    }

//    private MediaManager.VideoPlaybackStateListener updatedVideoPlaybackStateListener =
//            new MediaManager.VideoPlaybackStateListener() {
//                @Override
//                public void onUpdate(MediaManager.VideoPlaybackState videoPlaybackState) {
//                    updateStatusTextView(videoPlaybackState);
//                }
//            };

    private void getFileList() {
        manager = selectedCamera.getMediaManager();
        if (manager != null) {

            if ((currentFileListState == MediaManager.FileListState.SYNCING) || (currentFileListState == MediaManager.FileListState.DELETING)){
                DJILog.e(TAG, "Media Manager is busy.");
            }else{

                manager.refreshFileListOfStorageLocation(SettingsDefinitions.StorageLocation.SDCARD, new CommonCallbacks.CompletionCallback() {

                    @Override
                    public void onResult(DJIError djiError) {
                        if (null == djiError) {
                            hideProgressDialog();

                            //Reset data
                            if (currentFileListState != MediaManager.FileListState.INCOMPLETE) {
                                if (mediaFileList!=null){
                                    mediaFileList.clear();
                                    mediaFileList.addAll(manager.getSDCardFileListSnapshot());
                                    Collections.sort(mediaFileList, new Comparator<MediaFile>() {
                                        @Override
                                        public int compare(MediaFile lhs, MediaFile rhs) {
                                            if (lhs.getTimeCreated() < rhs.getTimeCreated()) {
                                                return 1;
                                            } else if (lhs.getTimeCreated() > rhs.getTimeCreated()) {
                                                return -1;
                                            }
                                            return 0;
                                        }
                                    });
                                }
                            }
                            scheduler.resume(new CommonCallbacks.CompletionCallback() {
                                @Override
                                public void onResult(DJIError error) {
                                    if (error == null) {
                                        getThumbnails();
                                    }
                                }
                            });
                        } else {
                            hideProgressDialog();
                            OnUIUtils.setToast("Get Media File List Failed:" + djiError.getDescription());
                        }
                    }
                });
            }
        }
    }

    private void getThumbnailByIndex(final int index) {
        FetchMediaTask task = new FetchMediaTask(mediaFileList.get(index), FetchMediaTaskContent.THUMBNAIL, taskCallback);
        scheduler.moveTaskToEnd(task);
    }

    private void getThumbnails() {
        if (mediaFileList.size() <= 0) {
            OnUIUtils.setToast("No File info for downloading thumbnails");
            return;
        }
        for (int i = 0; i < mediaFileList.size(); i++) {
            getThumbnailByIndex(i);
        }
    }

    private FetchMediaTask.Callback taskCallback = new FetchMediaTask.Callback() {
        @Override
        public void onUpdate(MediaFile file, FetchMediaTaskContent option, DJIError error) {
            if (null == error) {
                if (option == FetchMediaTaskContent.PREVIEW) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            adapter.notifyDataSetChanged();
                            mPbFetch.setVisibility(View.GONE);
                        }
                    });
                }
                if (option == FetchMediaTaskContent.THUMBNAIL) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            adapter.notifyDataSetChanged();
                            mPbFetch.setVisibility(View.GONE);
                        }
                    });
                }
            } else {
                DJILog.e(TAG, "Fetch Media Task Failed" + error.getDescription());
            }
        }
    };

}
